<?php

namespace App\Http\Controllers\RongCloud;

use App\Http\Controllers\ApiController;
use App\User;
use Illuminate\Http\Request;

class MessageController extends ApiController
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'from_user' => 'required|numeric',
            'to_user'   => 'required|numeric',
            'msg_type'  => 'required|in:img,txt',
            'chat_type' => 'required|in:chat,groupchat',
            'msg'       => 'required_if:msg_type,txt',
            'url'       => 'required_if:msg_type,img',
        ]);

        $now = time();

        $from_user = $request->input('from_user');
        $to_user   = $request->input('to_user');

        $pair = User::withoutGlobalScope('role')->whereIn('account', [$from_user, $to_user])->get(
            ['account', 'type']
        )->keyBy('account');

        /** @var User $from */
        /** @var User $to */
        $from = $pair->get($from_user);
        $to   = $pair->get($to_user);

        if ($from && $to) {
            \DB::table('tn_huanxin_chat')->insert([
                'type'      => 'chatmessage',
                'created'   => $now,
                'modified'  => $now,
                'timestamp' => $now,
                'addtime'   => date('Y-m-d H:i:s', $now),
                'from'      => $from->isPatient() ? 'patient_' . $from->account : 'doctor_' . $from->account,
                'to'        => $to->isPatient() ? 'patient_' . $to->account : 'doctor_' . $to->account,
                'msg'       => $request->input('msg') ?: null,
                'url'       => $request->input('url') ?: null,
                'msg_type'  => $request->input('msg_type') ?: null,
                'chat_type' => $request->input('chat_type') ?: null,
            ]);

            return $this->setMessage('发送完成')->setCode(10000)->hasNoData();
        } else {
            return $this->setMessage('参数错误')->hasNoData();
        }
    }
}
